var cart = require('../../utils/cart.js');
//获取CMS内容api
function getCMSContent(contentId,callback){
  if (typeof (contentId) == 'undefined') return null;
  wx.request({
    url: getApp().globalData.host + 'content/detail',
    header: getApp().globalData.header,
    data: { 'contentId': contentId },
    method:'POST',
    success: function (res) {
      if (typeof (res.data) != 'undefined' && res.data != '') {
        callback(res.data);
      }
    }
  })
}

/**
 * [用户一键注册 ]
 * @param  {[string]}   iv            [加密算法的初始向量]
 * @param  {[string]}   encryptedData [包括敏感数据在内的完整用户信息的加密数据]
 * @param  {[string]}   returnType    [是否需要往回跳转,true是，false否]
 * @param  {[string]}   delta         [往回跳转层数]
 * @param  {[string]}   tokenKey      [若用户通过页面扫码注册，则页面直接登录]
 * @param  {Function}   callback      [回调函数] 目前用不着
 * @return {[type]}                 [description]
 */
function onekeyRegister(iv,encryptedData,returnType,delta,tokenKey,callback){
  if (typeof (iv) == 'undefined'||typeof (encryptedData) == 'undefined') return null;
  let that = this;
  let userName = getApp().globalData.wechatUser.nickName;
  //获取loginCode
  wx.login({
    success: function (resp) {
      wx.request({
        url: getApp().globalData.host + 'webapp/control/onekeyRegister',
        header: getApp().globalData.header,
        data: { iv: iv,encryptedData:encryptedData,userName:userName,token:tokenKey,wechatCode: resp.code},
        method:'POST',
        success: function (res) {
          if (typeof (res.data) != 'undefined' && res.data != '') {
            if(res.data.success){
              getApp().globalData.header.cookie = "YNITTC_SOURCE=WECHAT;YNITTC_SESSION_ID=" + res.data.token;
              getApp().globalData.platUser = res.data.user;
              wx.showToast({
                title: "注册成功",
                duration:1500
              })
              cart.register();
              if(returnType){//跳转回去
                wx.navigateBack({delta: delta})
              }else{
                //返回首页
                wx.switchTab({
                  url: '/pages/index/index'
                })
              }
            }else{
              wx.showModal({
                title: res.data.errorMsg,
                showCancel:false
              })
            }
            //callback(res.data);
          }else{
            wx.showModal({
              title: '注册失败，请使用普通方式注册或者联系客服。',
              showCancel:false
            })
          }
        }
      })
    }
  })
}

/**
 * [扫码登录] 用户确认登录网页版
 * @param  {[String]} tokenKey [token]
 * @return {[type]}          [description]
 */
function scanLogin(tokenKey){
  wx.request({
    url: getApp().globalData.host + 'webapp/control/scanLogin',
    header: getApp().globalData.header,
    data: { tokenKey:tokenKey},
    method:'POST',
    success: function (res) {
      if (typeof (res.data) != 'undefined' && res.data) {
        wx.showToast({
          title: "登录成功",
          duration: 1500
        })
      }else{
        wx.showModal({
          title: '登录失败。',
          showCancel:false
        })
      }
    }
  })
}


/**
 * [校验微信版本,无提示信息]
 * @param  {[Number]} versionRequire [最低版本要求]
 * @return {[boolean]}               [符合要求]
 */
function verifySDKVersionNoRemind(versionRequire){
  if(typeof(getApp().globalData.wechatVersion)!='undefined'&&getApp().globalData.wechatVersion.length>2){
    let ver = Number(getApp().globalData.wechatVersion.substr(0,3));
    if(ver<versionRequire){
      return false;
    }else{
      return true;
    }
  }else{
    return true;
  }
}

/**
 * [校验微信版本]
 * @param  {[Number]} versionRequire [最低版本要求]
 * @return {[boolean]}               [符合要求]
 */
function verifySDKVersion(versionRequire){
  if(typeof(getApp().globalData.wechatVersion)!='undefined'&&getApp().globalData.wechatVersion.length>2){
    let ver = Number(getApp().globalData.wechatVersion.substr(0,3));
    if(ver<versionRequire){
      wx.showModal({
        title: '提示',
        content:'当前微信版本不支持此功能，请升级微信。',
        showCancel:false
      })
      return false;
    }else{
      return true;
    }
  }else{
    return true;
  }
}

//获取广告banner
function  getAdvs(advType,callback){
  wx.request({
    url: getApp().globalData.host + 'webapp/business/advs',
    header: getApp().globalData.header,
    data:{advType:advType},
    method: 'POST',
    success: function (res) {
      if(null!=res.data&&typeof(res.data)!='undefined'){
        for(let i = 0;i<res.data.length;i++){
          let imgUrl = res.data[i].imgUrl;
          if(imgUrl.indexOf('ynittc.cn')==-1){
            res.data[i].imgUrl = getApp().globalData.imgHost + imgUrl;
          }
        }
        callback(res.data);
      }
    }
  })
}

/**
 * [确认生成订单]
 * @param  {[String]} skuId     [skuId]
 * @param  {[int]} quantity     [数量]
 * @param  {[Boolean]} isSample [是否品鉴装，true为是]
 */
function confirmOrder(skuId,quantity,isSample){
  if (getApp().globalData.platUser == null) {//用户未登录 跳转至登录页面
    wx.navigateTo({
      url: '../../pages/login/login'
    });
  } else {
    wx.request({
      url: getApp().globalData.host + 'webapp/orders/confirm.html',
      data: { skuId: skuId, quantity: quantity, isSample: isSample},
      header: getApp().globalData.header,
      success: function (res) {
        if (typeof (res.data) != 'undefined' && typeof (res.data.orderId) != 'undefined')
          wx.navigateTo({
            url: '../../pages/confirm/confirm?orderId=' + res.data.orderId
          });
        else {
          wx.showModal({
            title: '创建订单失败',
            content: res.data,
            showCancel: false
          })
        }
      }
    })
  }
}

function login(callback){
  wx.login({
    success: function (res) {
      wx.getUserInfo({
        success: function (resp) {
          getApp().globalData.wechatUser = resp.userInfo;
        }
      });
      //尝试登陆
      wx.request({
        url: getApp().globalData.host + '/webapp/control/auth.html',
        header: getApp().globalData.header,
        data: { userCode: res.code },
        success: function (loginRes) {
          if (loginRes.data.success){
            getApp().globalData.header.cookie = "YNITTC_SOURCE=WECHAT;YNITTC_SESSION_ID=" + loginRes.data.token;
            getApp().globalData.uploadHeader.cookie = "YNITTC_SOURCE=WECHAT;YNITTC_SESSION_ID=" + loginRes.data.token;
            getApp().globalData.jsonHeader.cookie = "YNITTC_SOURCE=WECHAT;YNITTC_SESSION_ID=" + loginRes.data.token;
            getApp().globalData.platUser = loginRes.data.user;
          }
        },
        complete:function(res){
          callback();
        }
      });
    }
  });
}


module.exports = {
  getCMSContent:getCMSContent,
  onekeyRegister: onekeyRegister,
  scanLogin:scanLogin,
  verifySDKVersion:verifySDKVersion,
  verifySDKVersionNoRemind:verifySDKVersionNoRemind,
  getAdvs:getAdvs,
  confirmOrder: confirmOrder,
  login:login
}